﻿using BotDetector.Core.Model;

namespace BotDetector.Core.Converter
{
    public class ConvertFromDynamicToResultItemList:IConverter<object, ResultItemList>
    {
        public ResultItemList Convert(object input)
        {
            dynamic json = input;
            string phrase = FindSearchedPhrase(json);
            ResultItemList resultItemList = new ResultItemList()
            {
                Phrase = phrase
            };

            if (json.queries.request[0].totalResults == 0)
            {
                return resultItemList;
            }

            foreach (var query in json.items)
            {
                ResultItem resultItem = CreateResultItem(query);
                resultItemList.Add(resultItem);
            }

            return resultItemList;
        }

        private ResultItem CreateResultItem(dynamic query)
        {
            ResultItem resultItem = new ResultItem()
            {
                Title = (string)query.title,
                Description = (string)query.snippet,
                Url = (string)query.link
            };

            return resultItem;
        }

        private string FindSearchedPhrase(dynamic json)
        {
            dynamic nextPage;
            if (json.queries.nextPage == null)
            {
                nextPage = json.queries.request;
            }
            else
            {
                nextPage = json.queries.nextPage;
            }

            return nextPage.First.searchTerms;
        }
  
    }
}
